#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
存档管理器
负责游戏数据的保存和加载
"""

import json
import os
import shutil
import time
from typing import Dict, Any, Optional

class SaveManager:
    """存档管理器"""
    
    def __init__(self, save_dir="saves"):
        self.save_dir = save_dir
        self.save_file = os.path.join(save_dir, "game_save.json")
        self.backup_file = os.path.join(save_dir, "game_save_backup.json")
        
        # 确保存档目录存在
        os.makedirs(save_dir, exist_ok=True)
    
    def save_game(self, game_data: Dict[str, Any]) -> bool:
        """保存游戏数据"""
        try:
            # 备份现有存档
            if os.path.exists(self.save_file):
                shutil.copy2(self.save_file, self.backup_file)
            
            # 添加时间戳
            save_data = {
                "timestamp": time.time(),
                "version": "1.0",
                "data": game_data
            }
            
            # 保存到文件
            with open(self.save_file, 'w', encoding='utf-8') as f:
                json.dump(save_data, f, indent=2, ensure_ascii=False)
            
            return True
            
        except Exception as e:
            print(f"保存游戏失败: {e}")
            return False
    
    def load_game(self) -> Optional[Dict[str, Any]]:
        """加载游戏数据"""
        # 尝试加载主存档
        game_data = self._load_from_file(self.save_file)
        
        if game_data is None:
            # 主存档失败，尝试加载备份
            print("主存档损坏，尝试加载备份存档...")
            game_data = self._load_from_file(self.backup_file)
            
            if game_data is not None:
                print("备份存档加载成功")
                # 恢复主存档
                try:
                    shutil.copy2(self.backup_file, self.save_file)
                except:
                    pass
        
        return game_data
    
    def _load_from_file(self, filepath: str) -> Optional[Dict[str, Any]]:
        """从文件加载数据"""
        if not os.path.exists(filepath):
            return None
            
        try:
            with open(filepath, 'r', encoding='utf-8') as f:
                save_data = json.load(f)
                
            # 验证存档格式
            if "data" in save_data:
                return save_data["data"]
            else:
                # 旧格式兼容
                return save_data
                
        except Exception as e:
            print(f"存档文件读取失败 {filepath}: {e}")
            return None
    
    def delete_save(self) -> bool:
        """删除存档"""
        try:
            if os.path.exists(self.save_file):
                os.remove(self.save_file)
            if os.path.exists(self.backup_file):
                os.remove(self.backup_file)
            return True
        except Exception as e:
            print(f"删除存档失败: {e}")
            return False
    
    def has_save(self) -> bool:
        """检查是否有存档"""
        return os.path.exists(self.save_file)
    
    def get_save_info(self) -> Optional[Dict[str, Any]]:
        """获取存档信息"""
        if not self.has_save():
            return None
            
        try:
            with open(self.save_file, 'r', encoding='utf-8') as f:
                save_data = json.load(f)
                
            return {
                "timestamp": save_data.get("timestamp", 0),
                "version": save_data.get("version", "unknown"),
                "file_size": os.path.getsize(self.save_file)
            }
        except:
            return None